/**
 * TrackPlayer 后台播放服务
 * 处理通知栏按钮点击事件
 */

import TrackPlayer, { Event } from 'react-native-track-player';

module.exports = async function () {
  // 播放
  TrackPlayer.addEventListener(Event.RemotePlay, () => {
    TrackPlayer.play();
  });

  // 暂停
  TrackPlayer.addEventListener(Event.RemotePause, () => {
    TrackPlayer.pause();
  });

  // 停止
  TrackPlayer.addEventListener(Event.RemoteStop, () => {
    TrackPlayer.stop();
  });

  // 下一首
  TrackPlayer.addEventListener(Event.RemoteNext, () => {
    // 由 UI 层处理
  });

  // 上一首
  TrackPlayer.addEventListener(Event.RemotePrevious, () => {
    // 由 UI 层处理
  });

  // 快进
  TrackPlayer.addEventListener(Event.RemoteJumpForward, async event => {
    const position = await TrackPlayer.getPosition();
    await TrackPlayer.seekTo(position + (event.interval || 15));
  });

  // 快退
  TrackPlayer.addEventListener(Event.RemoteJumpBackward, async event => {
    const position = await TrackPlayer.getPosition();
    await TrackPlayer.seekTo(Math.max(0, position - (event.interval || 15)));
  });

  // 跳转到指定位置
  TrackPlayer.addEventListener(Event.RemoteSeek, event => {
    TrackPlayer.seekTo(event.position);
  });

  // 播放队列结束
  TrackPlayer.addEventListener(Event.PlaybackQueueEnded, () => {
    // 可以在这里处理播放完成的逻辑
  });

  // 播放错误
  TrackPlayer.addEventListener(Event.PlaybackError, error => {
    console.error('❌ PlaybackService 播放错误:', error);
  });
};
